package com.example.backend.service.async;

import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.TicketActionType;
import com.example.backend.service.EmailService;
import com.example.backend.service.TicketHistoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;

/**
 * 工单异步处理服务
 * 处理工单创建后的复杂业务逻辑，不阻塞主流程
 */
@Service
public class TicketAsyncService {
    
    private static final Logger log = LoggerFactory.getLogger(TicketAsyncService.class);
    
    @Autowired(required = false)
    private EmailService emailService;
    
    @Autowired
    private TicketHistoryService ticketHistoryService;
    
    /**
     * 异步处理工单创建后的业务逻辑
     * 
     * @param ticket 已创建的工单
     * @param creator 创建者
     * @return CompletableFuture<Void>
     */
    @Async("ticketAsyncExecutor")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public CompletableFuture<Void> handleTicketCreatedAsync(Ticket ticket, User creator) {
        String asyncId = "ASYNC-" + System.currentTimeMillis();
        
        try {
            log.info("╔═══════════════════════════════════════════════════════════════");
            log.info("║ [{}] 🚀 开始异步处理工单 - ID: {}", asyncId, ticket.getId());
            log.info("╠═══════════════════════════════════════════════════════════════");
            log.info("║ 线程: {}", Thread.currentThread().getName());
            log.info("║ 工单编号: {}", ticket.getTicketNumber());
            log.info("║ 工单标题: {}", ticket.getTitle());
            log.info("╚═══════════════════════════════════════════════════════════════");
            
            // 1. 创建工单历史记录
            createTicketHistory(asyncId, ticket, creator);
            
            // 2. 发送邮件通知
            sendEmailNotifications(asyncId, ticket, creator);
            
            // 3. 执行自动分配逻辑
            autoAssignTicket(asyncId, ticket);
            
            // 4. 触发工作流规则
            triggerWorkflowRules(asyncId, ticket);
            
            // 5. 更新统计信息
            updateStatistics(asyncId, ticket);
            
            log.info("╔═══════════════════════════════════════════════════════════════");
            log.info("║ [{}] ✅ 异步处理完成 - 工单ID: {}", asyncId, ticket.getId());
            log.info("╚═══════════════════════════════════════════════════════════════");
            
            return CompletableFuture.completedFuture(null);
            
        } catch (Exception e) {
            log.error("╔═══════════════════════════════════════════════════════════════");
            log.error("║ [{}] ❌ 异步处理失败 - 工单ID: {}", asyncId, ticket.getId());
            log.error("╠═══════════════════════════════════════════════════════════════");
            log.error("║ 异常: {}", e.getMessage());
            log.error("╚═══════════════════════════════════════════════════════════════");
            log.error("异常详情:", e);
            
            // 异步任务失败不影响主流程
            return CompletableFuture.failedFuture(e);
        }
    }
    
    /**
     * 创建工单历史记录
     */
    private void createTicketHistory(String asyncId, Ticket ticket, User creator) {
        try {
            log.debug("[{}] 步骤1: 创建工单历史记录...", asyncId);
            
            // 调用TicketHistoryService创建历史记录
            ticketHistoryService.createHistory(
                    ticket, 
                    creator, 
                    TicketActionType.CREATED, 
                    null,  // oldValue
                    ticket.getStatus().toString(),  // newValue
                    "status",  // fieldName
                    "工单已创建"  // description
            );
            
            log.info("[{}] ✅ 工单历史记录创建成功", asyncId);
            
        } catch (Exception e) {
            log.error("[{}] ❌ 创建工单历史记录失败: {}", asyncId, e.getMessage(), e);
            // 不抛出异常，继续后续处理
        }
    }
    
    /**
     * 发送邮件通知
     */
    private void sendEmailNotifications(String asyncId, Ticket ticket, User creator) {
        try {
            log.debug("[{}] 步骤2: 发送邮件通知...", asyncId);
            
            if (emailService != null) {
                log.info("[{}] ✅ 邮件通知功能已配置 - 目标收件人: {}", asyncId, creator.getEmail());
                // TODO: 根据EmailService的实际接口调整调用方式
                // emailService.sendTicketCreatedNotification(ticket, creator);
            } else {
                log.warn("[{}] ⚠️  EmailService未配置，跳过邮件发送", asyncId);
            }
            
        } catch (Exception e) {
            log.error("[{}] ❌ 发送邮件通知失败: {}", asyncId, e.getMessage(), e);
            // 不抛出异常，继续后续处理
        }
    }
    
    /**
     * 自动分配工单
     */
    private void autoAssignTicket(String asyncId, Ticket ticket) {
        try {
            log.debug("[{}] 步骤3: 执行自动分配逻辑...", asyncId);
            
            // TODO: 实现自动分配逻辑
            // 例如：根据工单分类、优先级、负载均衡等规则自动分配
            
            log.info("[{}] ✅ 自动分配逻辑执行完成", asyncId);
            
        } catch (Exception e) {
            log.error("[{}] ❌ 自动分配失败: {}", asyncId, e.getMessage(), e);
        }
    }
    
    /**
     * 触发工作流规则
     */
    private void triggerWorkflowRules(String asyncId, Ticket ticket) {
        try {
            log.debug("[{}] 步骤4: 触发工作流规则...", asyncId);
            
            // TODO: 实现工作流规则
            // 例如：触发SLA规则、升级规则、通知规则等
            
            log.info("[{}] ✅ 工作流规则触发完成", asyncId);
            
        } catch (Exception e) {
            log.error("[{}] ❌ 工作流规则触发失败: {}", asyncId, e.getMessage(), e);
        }
    }
    
    /**
     * 更新统计信息
     */
    private void updateStatistics(String asyncId, Ticket ticket) {
        try {
            log.debug("[{}] 步骤5: 更新统计信息...", asyncId);
            
            // TODO: 更新缓存中的统计信息
            // 例如：工单总数、分类统计、优先级统计等
            
            log.info("[{}] ✅ 统计信息更新完成", asyncId);
            
        } catch (Exception e) {
            log.error("[{}] ❌ 更新统计信息失败: {}", asyncId, e.getMessage(), e);
        }
    }
    
    /**
     * 异步发送WebSocket通知
     */
    @Async("commonAsyncExecutor")
    public CompletableFuture<Void> sendWebSocketNotification(Ticket ticket) {
        try {
            log.debug("📡 发送WebSocket通知 - 工单ID: {}", ticket.getId());
            
            // TODO: 实现WebSocket通知
            
            return CompletableFuture.completedFuture(null);
            
        } catch (Exception e) {
            log.error("❌ 发送WebSocket通知失败: {}", e.getMessage(), e);
            return CompletableFuture.failedFuture(e);
        }
    }
}

